package com.zzyl.intercept;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.UserVo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class AppUserTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    @Override //进入方法之前  判断当前登录人是否有次方法的权限  /user/add
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1、获取请求头中的token  注意请求头中的名字 authorization
        String token = request.getHeader(Constants.USER_TOKEN);
        if (StrUtil.isEmpty(token)) {
            //  如果请求头中没有token，提示重新登陆
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);

        }

        Claims claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), token);

        if (ObjectUtil.isEmpty(claims)) {
            //  token解析有问题
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);

        }
        // 从claims中获取用户数据     claims.put("currentUser", JSONUtil.toJsonStr(userVo));
        Long userId = claims.get(Constants.JWT_USERID, Long.class);
        if (ObjectUtil.isEmpty(userId)) {

            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);

        }

        // 把用户存储到ThreadLocal中

        // UserThreadLocal.setSubject(jsonStr);
        UserThreadLocal.set(userId);


        return true;

    }

    @Override//执行完方法之后
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

}
